package com.winning.ywypt.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.winning.ywypt.service.DataUploadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @ClassName: DataUploadServiceImpl
 * @Author: sujun@winning.com.cn
 * @Desc: TODO
 * @Date: 2018-12-20 15:12
 **/

@Service
public class DataUploadServiceImpl implements DataUploadService {

    private final Logger logger = LoggerFactory.getLogger(DataUploadServiceImpl.class);

    @Value("${com.winning.ywypt.tokenurl}")
    private String tokenurl;
    @Value("${com.winning.ywypt.posturl}")
    private String postnurl;
    @Value("${com.winning.ywypt.appid}")
    private String appid;
    @Value("${com.winning.ywypt.secret}")
    private String secret;

    @Autowired
    RestTemplate restTemplate;

    @Override
    public String getToken() throws Exception {

        logger.info("tokenurl:" + tokenurl + "appid=" + appid + "&secret=" + secret);
        String token = restTemplate.getForObject(tokenurl + "appid=" + appid + "&secret=" + secret, String.class);
        JSONObject tokenObject = JSON.parseObject(token);
        String code = tokenObject.getString("code");
        if (!"200".equals(code)) {
            throw new RuntimeException(tokenObject.getString("message"));
        }
        return tokenObject.getString("data");
    }

    @Override
    public void upLoadData(String token, String zbxxjson) {

        HttpHeaders headers = new HttpHeaders();
        //设置类型
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);

        HttpEntity<String> formEntity = new HttpEntity<String>(zbxxjson, headers);

        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(postnurl + "token=" + token + "&appid=" + appid, formEntity, String.class);
        String body = stringResponseEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(body);
        String code = jsonObject.getString("code");
        String message = jsonObject.getString("message");
        if (!"200".equals(code)) {
            logger.error(message);
            throw  new RuntimeException(message);
        }

    }
}
